import { Pool, PoolClient } from 'pg';
import Logger from './logger';
import { parseDbUrl } from './utilsJS'

require('dotenv').config();
const { host, database, user, password, port } = parseDbUrl(process.env.DATABASE_URL);

const pool = new Pool({
    user: user,
    host: host,
    password: password,
    port: port,
});

async function checkAndCreateDatabase(databaseName: string): Promise<void> {
    let client: PoolClient;
    try {
        client = await pool.connect();
        // 查询是否存在数据库
        const result = await client.query(`SELECT datname FROM pg_catalog.pg_database WHERE lower(datname) = lower('${databaseName}')`);
        if (result.rowCount === 0) {
            // 不存在，创建数据库
            await client.query(`CREATE DATABASE ${databaseName}`);
            console.log(`Database ${databaseName} has been created.`);
        } else {
            console.log(`Database ${databaseName} already exists.`);
        }
    } finally {
        // 释放客户端连接
        if (client) {
            client.release();
        }
    }
}

// 使用函数检查并创建数据库
checkAndCreateDatabase(database).catch(e => console.error(e.stack));